package com.maisonliberte.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.ContentBody;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreProtocolPNames;
import org.apache.http.util.EntityUtils;

import com.maisonliberte.conf.Config;

public class HttpUtil {
	
	public static String saveImage(String imageUrl) throws Exception{
		
		InputStream in = null;
		OutputStream out = null;
		String savedFilename = "";
		try { 
		
			URL url = new URL(imageUrl);  
			File file = new File(imageUrl.trim());
			String filename = file.getName();
			String localPath = Config.getInstance().imageSaveLocation;
			
			savedFilename = String.format("%s/%s", localPath, filename);
		    in = url.openStream();  
		    out = new FileOutputStream(savedFilename.trim());  
	        byte[] buf = new byte[1024];  
	        int len = 0;
	        while ((len = in.read(buf)) > 0) {    
	            out.write(buf, 0, len);  
	        }  
	  
	        out.flush();
	        System.out.println(savedFilename + " DOWNLOAD COMPLETED");
	    } catch(Exception ex){
	    	System.out.println(savedFilename + " DOWNLOAD FAILED");
	    	savedFilename = "";
	    } finally {  
	        if(out != null) out.close();  
	        if(in != null) in.close();  
	    }  
		
		return savedFilename;
	}
	
	public static String saveAsImage(String imageUrl, String localPath) throws Exception{
		
//		InputStream in = null;
//		OutputStream out = null;
//		String savedFilename = "";
//		try { 
//		
//			URL url = new URL(imageUrl);  
//			savedFilename = localPath;
//		    in = url.openStream();  
//		    out = new FileOutputStream(savedFilename.trim());  
//	        byte[] buf = new byte[1024];  
//	        int len = 0;
//	        while ((len = in.read(buf)) > 0) {    
//	            out.write(buf, 0, len);
//	        }  
//	  
//	        out.flush();
//	        System.out.println(savedFilename + " DOWNLOAD COMPLETED");
//	    } catch(Exception ex){
//	    	System.out.println(savedFilename + " DOWNLOAD FAILED" + ex.getMessage());
//	    	savedFilename = "";
//	    } finally {  
//	        if(out != null) out.close();  
//	        if(in != null) in.close();  
//	    }  
		String savedFilename = localPath;
		String filename = String.format("%s %s %s", Config.getInstance().downloadPHP, imageUrl, savedFilename);
	    try {
	      Process proc = Runtime.getRuntime().exec(filename);
	      proc.waitFor();
	    } catch( Exception e ) {
	    	savedFilename = "";
	    	System.out.println(e);
	    }
		
		return savedFilename;
	}
	
	public static String saveAsImage(String imageUrl, String localPath, String filename) throws Exception{
		
		InputStream in = null;
		OutputStream out = null;
		String savedFilename = "";
		try { 
		
			URL url = new URL(imageUrl);  
			File file = new File(imageUrl.trim());
			
			savedFilename = String.format("%s/%s", localPath, filename);
		    in = url.openStream();  
		    out = new FileOutputStream(savedFilename.trim());  
	        byte[] buf = new byte[1024];  
	        int len = 0;
	        while ((len = in.read(buf)) > 0) {    
	            out.write(buf, 0, len);  
	        }  
	  
	        out.flush();
	        System.out.println(savedFilename + " DOWNLOAD COMPLETED");
	    } catch(Exception ex){
	    	System.out.println(savedFilename + " DOWNLOAD FAILED" + ex.getMessage());
	    	savedFilename = "";
	    } finally {  
	        if(out != null) out.close();  
	        if(in != null) in.close();  
	    }  
		
		return savedFilename;
	}
		
	public static String httpGet(String _url, String encode) {
		 
		HttpURLConnection connection = null;
 
		try {

			URL url = new URL(_url);
			connection = (HttpURLConnection)url.openConnection();
			connection.setDoOutput(true);
			connection.setUseCaches(false);
			connection.setRequestMethod("GET");
			connection.setRequestProperty("Accept-Language","ja");
			BufferedReader bufferReader = new BufferedReader(new InputStreamReader(connection.getInputStream(), encode));
			String httpSource = new String();
			String str;
			while ( null != ( str = bufferReader.readLine() ) ) {
			    httpSource = httpSource + str;
			}
			bufferReader.close();
			connection.disconnect();
			
			return httpSource;
 
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (connection != null) {
				connection.disconnect();
			}
		}
		
		return "";
		
	}
	
	public static void upload(String url, String filename) throws Exception {
		try{
			
			HttpClient client = new DefaultHttpClient();
			client.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
			HttpPost        post   = new HttpPost( url );
			MultipartEntity entity = new MultipartEntity( HttpMultipartMode.BROWSER_COMPATIBLE );
			File file = new File(filename);
			ContentBody fileBody = new FileBody(file, "image/jpg");
			entity.addPart("userfile", fileBody);
			post.setEntity( entity );
			HttpResponse response = client.execute(post);
			
			// レスポンスヘッダーの取得
            System.out.println(response.getStatusLine().getStatusCode());
			
			// レスポンスボディの取得
            HttpEntity httpEntity = response.getEntity();
            System.out.println(EntityUtils.toString(httpEntity));
            
		}catch(Exception ex){
			throw ex;
		}
	}
	
	public static String uploadProduct(String url, String path, String filename) throws Exception {
		try{
			
			HttpClient client = new DefaultHttpClient();
			client.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
			HttpPost        post   = new HttpPost( url );
			MultipartEntity entity = new MultipartEntity( HttpMultipartMode.BROWSER_COMPATIBLE );
			File file = new File(filename);
			ContentBody fileBody = new FileBody(file, "image/jpg");
			entity.addPart("userfile", fileBody);
			entity.addPart("path", new StringBody(path.replace("/public_html/prod_images", "")));
			post.setEntity( entity );
			HttpResponse response = client.execute(post);
			
			// レスポンスヘッダーの取得
            System.out.println(response.getStatusLine().getStatusCode());
			
			// レスポンスボディの取得
            HttpEntity httpEntity = response.getEntity();
            System.out.println(EntityUtils.toString(httpEntity));
            
            String[] arrs = url.replace("http://", "").split("/");
            String imgUrl = arrs[0];
            imgUrl = String.format("http://%s%s%s", imgUrl, path.replace("/public_html", ""), FileUtil.getFilename(filename));
            
            return imgUrl;
            
		}catch(Exception ex){
			throw ex;
		}
	}
	
	
 
    public static void httpPost(String url, Map<String, String> requestParams) {
// 
//        HttpPost httpPost = null;
// 
//        try {
//            List<NameValuePair> params = new ArrayList<NameValuePair>();
//            for (Map.Entry<String, String> entry : requestParams.entrySet()) {
//                params.add(new BasicNameValuePair((String) entry.getKey(), (String) entry.getValue()));
//            }
// 
//            httpPost = new HttpPost(url);
//            httpPost.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
// 
//            System.out.println("executing request " + httpPost.getURI());
//            System.out.println("-------------------------------------");
// 
//            HttpResponse response = httpClient.execute(httpPost);
//            System.out.println(response.getStatusLine().getStatusCode());
// 
//            Header[] headers = response.getAllHeaders();
//            for (Header header : headers) {
//                System.out.println(header.getName() + ": " + header.getValue());
//            }
// 
//            System.out.print(System.getProperty("line.separator"));
// 
//            HttpEntity httpEntity = response.getEntity();
//            System.out.println(EntityUtils.toString(httpEntity));
// 
//        } catch (UnsupportedEncodingException e) {
//            e.printStackTrace();
//        } catch (ClientProtocolException e) {
//            e.printStackTrace();
//        } catch (IOException e) {
//            e.printStackTrace();
//        } finally {
//            if (httpPost != null) {
//                httpPost.abort();
//            }
//        }
    }
    
    public static boolean existsURL(String URLName){
        try {
          HttpURLConnection.setFollowRedirects(false);
          // note : you may also need
          //        HttpURLConnection.setInstanceFollowRedirects(false)
          HttpURLConnection con =
             (HttpURLConnection) new URL(URLName).openConnection();
          con.setRequestMethod("HEAD");
          return (con.getResponseCode() == HttpURLConnection.HTTP_OK);
        }
        catch (Exception e) {
           //e.printStackTrace();
           return false;
        }
    }
    
}
